import { WsClient } from "tsrpc";
import { getGameConfig } from "./gameConfigMgr";
import { gameServer } from "./server";
import { serviceProto, ServiceType } from "./shared/gameCluster/protocols/serviceProto";
import { logger } from "./shared/tsgf/logger";

/**
 * 获取游戏服务器集群客户端
 * @param serverUrl 服务器地址
 * @returns 
 */
export function getGameClusterClient(): WsClient<ServiceType> {
    var serverCfg = getGameConfig();
    var client = new WsClient(serviceProto, {
        server: serverCfg.gameServer.gameClusterServerWSUrl,//gatecluster.iclouden.com
        json: false,
        logger: logger,
    });
    var autoSyncGameInfoHD = setInterval(() => {
        if(!client.isConnected){
            clearInterval(autoSyncGameInfoHD);
            return;
        }
        client.sendMsg("SyncServerInfo", {
            serverInfo: {
                serverId: serverCfg.gameServer.serverId,
                serverName: serverCfg.gameServer.serverName,
                serverWSUrl: serverCfg.gameServer.serverWSUrl,
                clientCount: gameServer.connections.length,
                extendData: serverCfg.gameServer.extendData,
            }
        });
    }, 1000);
    client.flows.postDisconnectFlow.push(v => {
        clearInterval(autoSyncGameInfoHD);
        return v;
    });

    return client;
}